<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <style>
    .listBox {
      height: 200px;
      overflow: auto;
      background: pink;
      width: 200px;
    }

    .list {
      height: 50px;
    }
  </style>
  <body>
    <div id="app"></div>

    <script src="../utils/js/news/react.development.js"></script>
    <script src="../utils/js/news/react-dom.development.js"></script>
    <script src="../utils/js/news/babel.min.js"></script>
    <script src="../utils/js/news/prop-types.js"></script>

    <script type="text/babel">
      class Newlist extends React.Component {
        state = { newArr: [] };

        componentDidMount() {
          this.timeID = setInterval(() => {
            const { newArr } = this.state;
            const news = `列表${newArr.length + 1}`;
            this.setState({ newArr: [news, ...newArr] });
          }, 2000);
        }

        render() {
          const { newArr } = this.state;
          return (
            <div className="listBox" ref="list">
              {newArr.map((item, index) => (
                <div key={index} className="list">
                  {item}
                </div>
              ))}
            </div>
          );
        }

        getSnapshotBeforeUpdate() {
          // 获取内容高度
          return this.refs.list.scrollHeight;
        }

        componentDidUpdate(preProps, preStates, snapshot) {
          // 滚动条垂直的偏移量
          console.log(this.refs.list.scrollTop);
          // 滚动条垂直的偏移量 始终是新增加的高度+内容的高度
          this.refs.list.scrollTop =
            this.refs.list.scrollTop + this.refs.list.scrollHeight - snapshot;
        }
      }

      ReactDOM.render(<Newlist />, document.getElementById("app"));
    </script>
  </body>
</html>
